package com.yndsoft.jc.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yndsoft.jc.MainActivity;
import com.yndsoft.jc.R;
import com.yndsoft.jc.activity.BaseFragment;
import com.yndsoft.jc.core.ActivitiesManager;
import com.yndsoft.jc.model.Ad;
import com.yndsoft.jc.model.Cart;
import com.yndsoft.jc.model.Member;
import com.yndsoft.jc.model.Order;
import com.yndsoft.jc.model.OrderDet;
import com.yndsoft.jc.model.ReturnMsg;
import com.yndsoft.jc.supplier.utils.ToastUtil;
import com.yndsoft.jc.ui.memberpage.login.LoginActivity;
import com.yndsoft.jc.ui.net.util.ProgressSubscriber;
import com.yndsoft.jc.ui.shoppingcart.ConfirmOrderActivity;
import com.yndsoft.jc.ui.shoppingcart.ShoppingDetailAdapter;
import com.yndsoft.jc.ui.shoppingcart.entity.CartBean;
import com.yndsoft.jc.ui.shoppingcart.entity.ShoppingItemBean;
import com.yndsoft.jc.widget.AutoSwipeRefreshLayout;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * Created by hasee on 2017/12/3.
 */

public class CartFragment extends BaseFragment implements View.OnClickListener, ShoppingDetailAdapter.CheckInterface {

    private static final String TAG = "CartFragment";
    @Bind(R.id.cart_swipe)
    AutoSwipeRefreshLayout cart_swipe;

    @Bind(R.id.cartbackBtn)
    ImageView backBtn;
    @Bind(R.id.cart_editBtn)
    TextView cart_editBtn;
    private boolean editAble = false;
    @Bind(R.id.shopping_details)
    ListView shopping_details;
    @Bind(R.id.ck_all)
    CheckBox ck_all;//全选按钮
    @Bind(R.id.layout_total)
    LinearLayout layout_total;//合计的父布局
    @Bind(R.id.tv_show_price)
    TextView tv_show_price;//合计金额
    @Bind(R.id.close_an_account)
    LinearLayout close_an_account;
    @Bind(R.id.delete_account)
    TextView delete_account;
    //结算文字点编辑改成删除项目

    List<OrderDet> list = new ArrayList<>();
    ShoppingDetailAdapter adapter;

    @Bind(R.id.empty_layout)
    LinearLayout empty_layout;
    @Bind(R.id.go_to_stroll)
    Button go_to_stroll;

    @Override
    public int getContentResouceId() {
        return R.layout.fragment_cart;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setViews();
        setListener();
    }

    private void setListener() {
        cart_editBtn.setOnClickListener(this);
        close_an_account.setOnClickListener(this);
        ck_all.setOnClickListener(this);
        cart_swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (mSession.isLogin()) {
                    getDatas();
                } else {
                    ToastUtil.show(context, "请先登录");
                    cart_swipe.setRefreshing(false);
                }
            }
        });
        go_to_stroll.setOnClickListener(this);

    }

    private void setViews() {
        cart_swipe.setColorSchemeColors(getResources().getColor(R.color.colorAccent));

        adapter = new ShoppingDetailAdapter(context);
        adapter.setCheckInterface(this);
        shopping_details.setAdapter(adapter);
        shopping_details.setEmptyView(empty_layout);
        getDatas();
    }

    private void getDatas() {
//        SharedPreferences sp = context.getSharedPreferences(getString(R.string.sp_member), Context.MODE_PRIVATE);
//        Type type = new TypeToken<Member>() {
//        }.getType();
//        Object fromJson = new Gson().fromJson(sp.getString(getString(R.string.sp_jc), ""), type);
//        Member member = (Member) fromJson;
        if ((mSession.getRole() == 1) && (mSession.isLogin())) {
            mHttpUtil.getMemberCart(new ProgressSubscriber<ReturnMsg>(context) {
                @Override
                public void next(ReturnMsg returnMsg) {
                    list.clear();
                    Type type = new TypeToken<List<OrderDet>>() {
                    }.getType();
                    Object fromJson = new Gson().fromJson(returnMsg.getInfo(), type);
                    if (null != fromJson) {
                        list = (ArrayList<OrderDet>) fromJson;
                    }
                    adapter.setData(list);
                }
            }, "cart", mSession.getUserInfo().getId());
            if (cart_swipe != null) {
                cart_swipe.setRefreshing(false);
            }
        } else {
//            startActivity(new Intent(context, LoginActivity.class));
            ToastUtil.show(context, "请先登录");
        }
    }

    @Override
    public String getFragmentName() {
        return "CartFragment";
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cart_editBtn:
                showTotalPrice();
                break;
            case R.id.close_an_account:
                if (!editAble) {//此时显示的是去结算
                    if (totalWeight == 0) {
                        ToastUtil.show(context, "请选择项目！");
                    } else {
                        lementOnder();
                    }
                } else {//此时现实的是删除
                    deleteItem();
                }
                break;
            case R.id.ck_all:
                if (list.size() != 0) {
                    if (ck_all.isChecked()) {
                        for (int i = 0; i < list.size(); i++) {
                            list.get(i).setChoose(true);
                        }
                        adapter.notifyDataSetChanged();
                    } else {
                        for (int i = 0; i < list.size(); i++) {
                            list.get(i).setChoose(false);
                        }
                        adapter.notifyDataSetChanged();
                    }
                }
                statistics();
                break;
            case R.id.go_to_stroll:
                MainActivity mainActivity = (MainActivity) ActivitiesManager.getInstance().getSpecialActivity(MainActivity.class);
                mainActivity.clickIndex();
                break;
        }
    }

    List<OrderDet> deleteList = new ArrayList<>();

    private void deleteItem() {
        deleteList.clear();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isChoose()) {
//                list.remove(i);
                deleteList.add(list.get(i));
            }
        }
        mHttpUtil.deleteCartItem(new ProgressSubscriber<ReturnMsg>(context) {
            @Override
            public void next(ReturnMsg returnMsg) {
                switch (returnMsg.getCode()) {
                    case 0:
                        ToastUtil.show(context, "删除失败");
                        break;
                    case 1:
                        getDatas();
                        break;

                }
            }
        }, "deletecart", mSession.getUserInfo().getId(), new Gson().toJson(deleteList));
//        adapter.setData(list);
    }

    private List<OrderDet> resultList = new ArrayList<>();
    private String key = "MyOrder";
    private Order order;

    /**
     * 结算订单、支付
     */
    private void lementOnder() {
        resultList.clear();
        order = new Order();
        //选中的需要提交的商品清单
        for (OrderDet bean : list) {
            boolean choosed = bean.isChoose();
            if (choosed) {
                resultList.add(bean);
            }
        }
        order.setDets(resultList);
        Toast.makeText(context, "总价：" + totalPrice, Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(context, ConfirmOrderActivity.class);
        intent.putExtra("MyOrder", order);
        intent.putExtra("ctype", 1);
        startActivity(intent);

        //跳转到支付界面
    }

    /**
     * 点击编辑的操作
     */
    private void showTotalPrice() {
        if (!editAble) {
            setEmptyStatus();
            cart_editBtn.setText("完成");
            layout_total.setVisibility(View.INVISIBLE);
            delete_account.setText("删除");
            editAble = true;
        } else {
            setEmptyStatus();
            cart_editBtn.setText("编辑");
            layout_total.setVisibility(View.VISIBLE);
            delete_account.setText("去结算");
            editAble = false;
        }
    }

    private void setEmptyStatus() {
        for (int x = 0; x < list.size(); x++) {
            list.get(x).setChoose(false);
        }
        adapter.setData(list);
        statistics();
    }

    @Override
    public void checkGroup(int position, boolean isChecked) {
        list.get(position).setChoose(isChecked);
        if (isAllCheck())
            ck_all.setChecked(true);
        else
            ck_all.setChecked(false);
        adapter.notifyDataSetChanged();
        statistics();
    }

    /**
     * 遍历list集合
     *
     * @return
     */
    private boolean isAllCheck() {

        for (OrderDet group : list) {
            if (!group.isChoose())
                return false;
        }
        return true;
    }


    private double totalPrice = 0.00;// 购买的商品总价
    private int totalWeight = 0;

    /**
     * 统计操作
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作
     * 3.给底部的textView进行数据填充
     */
    public void statistics() {
        totalPrice = 0.00;
        totalWeight = 0;
        for (int i = 0; i < list.size(); i++) {
            OrderDet shoppingCartBean = list.get(i);
            if (shoppingCartBean.isChoose()) {
                totalPrice += shoppingCartBean.getProductattribute().getPrice();
                totalWeight += shoppingCartBean.getProductattribute().getLimit();
            }
        }
        tv_show_price.setText(totalPrice + "");
    }

    @Override
    public void onResume() {
        super.onResume();
        getDatas();
    }
}
